package dbPicasso::UI::Dialog::dlgFind;

use base qw(dbPicasso::UI::Dialog);

our $DIALOG;
our $DB_CONN;

our $LAST_SEARCH;
our $LAST_REPLACE;

sub show
{
    my $class = shift;
    $DB_CONN = shift;

    Gtk2::Rc->parse_string(
        'style "liststyle" { GtkComboBoxEntry::appears-as-list = 1 }
				 widget "*.LoadObjectName" style "liststyle"');

    $DIALOG = $class->SUPER::show("dlgFind", __PACKAGE__, undef, \&init_dialog);
}

sub init_dialog
{
    my ($dlgref, $dlgdef) = @_;

    $DIALOG  = $dlgdef;
	
	my $find = $DIALOG->get_widget('FindText');
	$find->set_text($LAST_SEARCH);
	
}

sub on_btnFind_clicked
{
    my $findentry = $DIALOG->get_widget('FindText');
    my $direction;
    
    $findtxt = $findentry->get_text;
    
    if ($LAST_SEARCH eq $findtxt)
    { 
    	$direction = 1;
    } 
    else
    {
    	$LAST_SEARCH = $findtxt;
    }
    
    &search_buffer($dbPicasso::UI::CODE, $findtxt, $direction);

}

sub on_btnReplace_clicked
{
    my $findtxt  = $DIALOG->get_widget('FindText');
    my $replwith = $DIALOG->get_widget('ReplaceWith');

}

# Initially borrowed from http://svn1.hostlocal.com/szabgab/trunk/gtk2/gtk-perl-demo.pl
# and hammered into dbPicasso. 
sub search_buffer {
	my ($textview, $text, $direction) = @_;
	
	my $buffer = $textview->get_buffer;

	my $cont = $buffer->get_text($buffer->get_start_iter, $buffer->get_end_iter, 0);
	my $start_index = 0;
	
	if ($direction) {
		my $mark = $buffer->get_selection_bound;
		my $iter = $buffer->get_iter_at_mark($mark);
		$start_index = $iter->get_offset;
	}

	my $start = index ($cont, $text, $start_index);
	return if $start == -1;

	my $start_iter = $buffer->get_iter_at_offset($start);
	my $end_iter   = $buffer->get_iter_at_offset($start+length($text));
	$buffer->select_range($start_iter, $end_iter);

	my $mark = $buffer->create_mark("xxx", $start_iter, TRUE);
	$textview->scroll_to_mark($mark, 0.4, TRUE, 0.5, 0.5);
}



1;
